package xcmg.device.web.minio.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.web.minio.config.MinioUtil;
import yb.ecp.fast.infra.infra.ActionResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/minio")
@RefreshScope
public class MinioController extends BasicController {
    @Value("${file.upload.qualityStr:0.2}")
    private String qualityStr;

    @Value("${file.upload.bucketName:gcwms}")
    private String bucketName;

    @Autowired
    MinioUtil minioUtil;

    @PostMapping("/uploadImg")
    public ActionResult<Object> uploadImage(@RequestParam("imgFile") MultipartFile imgFile) throws Exception {
        Map<String, Object> result = minioUtil.uploadImgFile(imgFile, bucketName, qualityStr);
        if (result != null) {
            return actionValueResult(result);
        }
        throw new CommonBusiExceptions(ErrorCode.Failure.getDesc());
    }

    @PostMapping("/uploadFile")
    public ActionResult<Object> uploadFile(HttpServletRequest request, @RequestParam(defaultValue = "true", required = false) boolean dataPath) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        try {
            Map<String, Object> result = minioUtil.uploadFile(file, bucketName);
            if (result != null) {
                return actionValueResult(result);
            }
        } catch (Exception e) {
            throw new CommonBusiExceptions(e.getMessage());
        }
        throw new CommonBusiExceptions(ErrorCode.Failure.getDesc());
    }

    @GetMapping("/downloadFile")
    public void downloadFile(@RequestParam("fileName") String filename, HttpServletResponse response) throws Exception {
        minioUtil.getObject(bucketName, filename, response);
    }
}
